package com.yuyuan.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yuyuan.api.client.NoticeClient;
import com.yuyuan.api.domain.EventDTOC;
import com.yuyuan.api.domain.NoticeDTOC;
import com.yuyuan.api.client.UserClient;
import com.yuyuan.blog.domain.Event;
import com.yuyuan.blog.domain.po.Likes;
import com.yuyuan.blog.mapper.CommentMapper;
import com.yuyuan.blog.mapper.DailyBlogMapper;
import com.yuyuan.blog.mapper.LikeMapper;
import com.yuyuan.blog.service.ILikeService;
import com.yuyuan.blog.utils.IdGenerator;
import com.yuyuan.common.domain.Result;
import com.yuyuan.common.utils.RedisConstants;
import com.yuyuan.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.yuyuan.blog.utils.CommunityConstant.ENTITY_TYPE_LIKE;
import static com.yuyuan.blog.utils.CommunityConstant.TOPIC_LIKE;


/**
 * @Author: kestrel
 * @Version:1.0
 * @Date: 2024/6/20
 */
@Slf4j
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Likes> implements ILikeService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DailyBlogMapper dailyBlogMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private NoticeClient noticeClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result likeComment(Long commentId) {
        Long userId = UserHolder.getUser().getId();
        String type;
        if (checkIfLike(userId, commentId)) {
            commentMapper.addLike(commentId);
            Likes likes = new Likes(idGenerator.nextLikeId(), "comment", commentId, userId, LocalDateTime.now());
            likeMapper.insert(likes);

            // 触发点赞通知事件
            type = "点赞成功";
            long blogId = commentMapper.selectById(commentId).getBlogId();
            long receiveId  = commentMapper.selectById(commentId).getUserId();
            String name = userClient.selectById(userId).getName();
            NoticeDTOC noticeDTOC = new NoticeDTOC(idGenerator.nextNoticeId(),blogId,userId,receiveId,LocalDateTime.now(),
                    "comment","用户" + name + "点赞了" + blogId + "评论:" + commentMapper.selectById(commentId).getContent());
            Event event = new Event(
                    TOPIC_LIKE,
                    UserHolder.getUser().getId(),
                    ENTITY_TYPE_LIKE,
                    blogId,
                    noticeDTOC,
                    "Notice");
            noticeClient.fireEvent(BeanUtil.copyProperties(event, EventDTOC.class));

        } else {
            commentMapper.subLike(commentId);
            QueryWrapper<Likes> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("type", "comment")
                    .eq("user_id", userId)
                    .eq("like_id", commentId);
            remove(queryWrapper);
            type = "取消点赞成功";
        }
        return Result.ok(type);
    }

    @Override
    public Result likeBlog(Long blogId) {
        Long userId = UserHolder.getUser().getId();
        String type;
        if (checkIfLike(userId, blogId)) {
            dailyBlogMapper.addLike(blogId);
            Likes likes = new Likes(idGenerator.nextLikeId(), "blog", blogId, userId, LocalDateTime.now());
            likeMapper.insert(likes);
            type = "点赞成功";

            // 触发点赞通知事件
            long receiveId  = dailyBlogMapper.selectById(blogId).getUserId();
            String name = userClient.selectById(userId).getName();
            NoticeDTOC noticeDTOC = new NoticeDTOC(idGenerator.nextNoticeId(),blogId,userId,receiveId,LocalDateTime.now(),
                    "comment","用户" + name + "点赞了" + blogId + "博客:" + dailyBlogMapper.selectById(blogId).getContent());
            Event event = new Event(
                    TOPIC_LIKE,
                    UserHolder.getUser().getId(),
                    ENTITY_TYPE_LIKE,
                    blogId,
                    noticeDTOC,
                    "Notice");
            noticeClient.fireEvent(BeanUtil.copyProperties(event, EventDTOC.class));

            // 缓存分数状态变更帖子id
            redisTemplate.opsForSet().add(RedisConstants.getPostScoreKey(), blogId);
        } else {
            dailyBlogMapper.subLike(blogId);
            QueryWrapper<Likes> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("type", "blog")
                    .eq("user_id", userId)
                    .eq("like_id", blogId);
            remove(queryWrapper);
            type = "取消点赞成功";
        }
        return Result.ok(type);
    }

    @Override
    public boolean checkIfLike(Long userId, Long likeId) {
        QueryWrapper<Likes> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("like_id", likeId)
                .eq("user_id", userId);
        return likeMapper.selectList(queryWrapper).isEmpty();
    }
}
